package com.example.newsapp.view.activity;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.newsapp.R;
import com.example.newsapp.viewmodel.UserViewModel;

public class RegisterActivity extends AppCompatActivity {
    private UserViewModel userViewModel;
    private EditText editTextUsername, editTextPassword, editTextConfirmPassword, editTextEmail;
    private TextView textViewBackToLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);

        // 初始化视图
        editTextUsername = findViewById(R.id.editTextRegUsername);
        editTextPassword = findViewById(R.id.editTextRegPassword);
        editTextConfirmPassword = findViewById(R.id.editTextRegConfirmPassword);
        editTextEmail = findViewById(R.id.editTextEmail);
        Button buttonRegister = findViewById(R.id.buttonConfirmRegister);
        textViewBackToLogin = findViewById(R.id.textViewBackToLogin);

        // 注册按钮点击事件
        buttonRegister.setOnClickListener(v -> {
            String username = editTextUsername.getText().toString().trim();
            String password = editTextPassword.getText().toString().trim();
            String confirmPassword = editTextConfirmPassword.getText().toString().trim();
            String email = editTextEmail.getText().toString().trim();

            // 输入验证
            if (username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty() || email.isEmpty()) {
                Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show();
                return;
            }

            // 密码匹配验证
            if (!password.equals(confirmPassword)) {
                Toast.makeText(this, "两次输入的密码不匹配", Toast.LENGTH_SHORT).show();
                return;
            }

            // 邮箱格式验证
            if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
                Toast.makeText(this, "请输入有效的邮箱地址", Toast.LENGTH_SHORT).show();
                return;
            }

            // 执行注册
            userViewModel.register(username, password, email);
        });

        // 返回登录页面
        textViewBackToLogin.setOnClickListener(v -> finish());

        // 观察注册结果
        userViewModel.getRegisterResult().observe(this, result -> {
            Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
            if (result.equals("Registration successful")) {
                finish();
            }
        });
    }
}